﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _2_12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private double GetPacket(ref double total, int n)
        {
            if (n == 1)
                return Math.Round(total, 2);

            Random rnd = new Random();
            double avg = Math.Round(total / n, 2);
            // 在平均值的0.5倍到1.5倍之间随机
            double thisPacket = avg / 2 + avg * rnd.Next(101) / 100.0;
            thisPacket = Math.Round(thisPacket, 2);
            total -= thisPacket;
            total = Math.Round(total, 2);
            return thisPacket;
        }
        private double SumPacket(double[] a)
        {
            double sum = 0;
            foreach (double m in a)
                sum += m;
            return Math.Round(sum, 2);
        }

        private void btnDistribute_Click(object sender, EventArgs e)
        {
            try
            {
                double total = double.Parse(txtTotal.Text);
                int n = int.Parse(txtCount.Text);

                if (total <= 0 || n <= 0)
                {
                    MessageBox.Show("红包金额和个数必须大于0！");
                    return;
                }

                double[] redPacket = new double[n];
                double currentTotal = total;

                for (int i = n; i > 0; i--)
                {
                    redPacket[n - i] = GetPacket(ref currentTotal, i);
                }

                // 显示红包
                txtPackets.Text = string.Join(Environment.NewLine, redPacket);
                // 显示总和
                txtSum.Text = SumPacket(redPacket).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("请输入有效的数值！");
            }
        }
    }
}
